<template>
  <div>
    <el-card>
      <el-form :model="user" :rules="rules" ref="CompanyInfo">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model.trim="user.companyName" :readonly="userInfo.status === 1 || userInfo.status === 3"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" :xs="24">
            <el-form-item v-if="user.type === 2" label="企业类型">
              <el-select v-model="user.companyType">
                <el-option v-for="item in companyTypeJson" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12" :xs="24">
            <el-form-item label="纳税人识别号" prop="taxNo">
              <el-input v-model.trim="user.taxNo" :readonly="userInfo.status === 1 || userInfo.status === 3"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="业务联系人" prop="companyContactName">
              <el-input v-model.trim="user.companyContactName" :readonly="userInfo.status === 1 || userInfo.status === 3"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="联系人电话" prop="companyContactMobile">
              <el-input v-model.trim="user.companyContactMobile" :readonly="userInfo.status === 1 || userInfo.status === 3"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="所在城市">
          <AddressCascader ref="addressCascader" v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model.trim="user.companyAddress" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="主营分类">
          <Cascader v-model="companySaleCategorys" :options="categoryData" :ids="companySaleCategoryIds" :props="props"
            ref="companySaleCategorys" />
        </el-form-item>
        <el-form-item label="主要采购">
          <Cascader v-model="companyBuyCategorys" :options="categoryData" :ids="companyBuyCategoryIds" :props="props"
            ref="companyBuyCategorys" />
        </el-form-item> -->
        <el-form-item label="营业执照图片" prop="authImage">
          <div style="display:flex;align-items: center;">
            <Upload :default-image.sync="user.authImage" :mode="6" :size="2" />
            <span style="margin-left:30px;color:#ff8704;">文件大小限制2Mb</span>
          </div>
        </el-form-item>
        <el-form-item label="法人身份证人像面" prop="cardImage">
          <div style="display:flex;align-items: center;">
            <Upload :default-image.sync="user.cardImage" :mode="6" :size="2" />
            <span style="margin-left:30px;color:#ff8704;">文件大小限制2Mb</span>
          </div>
        </el-form-item>
        <el-form-item label="门头照" prop="doorImage">
          <div style="display:flex;align-items: center;">
            <Upload :default-image.sync="user.doorImage" :mode="6" :size="2" />
            <span style="margin-left:30px;color:#ff8704;">文件大小限制2Mb</span>
          </div>
        </el-form-item>
        <el-form-item label="其他证明图片">
          <UpImgs :default-image.sync="otherImages" :size="1" :limit="5" />
          <div style="display:flex;align-items: center;">
            <span style="margin-left:30px;color:#ff8704;">图片原文件大小需控制在1M以内，支持jpg、gif、png、bmp</span>
          </div>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="authNo">
          <el-input v-model.trim="user.authNo" placeholder='统一社会信用代码' :readonly="userInfo.status === 1 || userInfo.status === 3"/>
        </el-form-item>
        <el-form-item label="法人身份证号码" prop="cardNo">
          <el-input v-model.trim="user.cardNo" placeholder='法人身份证号码' :readonly="userInfo.status === 1 || userInfo.status === 3"/>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo"> 
          <el-input v-model.trim="user.contractNo" :readonly="userInfo.status === 1 || userInfo.status === 3"/>
        </el-form-item>
        <el-form-item v-if="userInfo.status === 2 || userInfo.status === 5">
          <el-button type="primary" @click="submit('CompanyInfo')" >提交认证</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top:20px">
      <el-form :model="user" :rules="baseRules" ref="baseInfo">
        <el-row :gutter="20">
          <!-- <el-col :span="12" :xs="24">
            <el-form-item label="企业名称">
              <el-input v-model.trim="user.companyName" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" :xs="24">
            <el-form-item label="商户编号">
              <el-input v-model.trim="user.identifier" readonly />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12" :xs="24">
            <el-form-item v-if="user.type === 2" label="企业类型">
              <el-select v-model="user.companyType">
                <el-option v-for="item in companyTypeJson" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="业务联系人">
              <el-input v-model.trim="user.companyContactName" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="联系人电话">
              <el-input v-model.trim="user.companyContactMobile" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="企业性质" prop="companyMature">
              <el-select v-model="user.companyMature">
                <el-option v-for="item in companyMatureData" :key="item.value" :label="item.value" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="企业规模" prop="companyScale">
              <el-select v-model="user.companyScale">
                <el-option v-for="item in companyScaleData" :key="item.value" :label="item.value" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="企业邮箱" prop="companyEmail">
              <el-input v-model.trim="user.companyEmail" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="企业电话">
              <el-input v-model.trim="user.companyMobile" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="企业官网">
              <el-input v-model.trim="user.companySite" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="企业传真">
              <el-input v-model.trim="user.companyTax" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="所在城市" prop="selectedOptions">
              <AddressCascader ref="addressCascader" v-model="user.selectedOptions" @selectAddressDetail="selectAddressDetail" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="微信公众号">
              <el-input v-model.trim="user.companyWeixin" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form-item label="详细地址" prop="companyAddress">
              <el-input v-model.trim="user.companyAddress" type="textarea" :rows="3" />
            </el-form-item>
            <el-form-item label="注册资本" prop="companyMoney">
              <div class="flexInput">
                <el-input v-model.trim="user.companyMoney" type="number" />万元
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="企业LOGO">
              <Upload :default-image.sync="user.companyLogo" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item label="主营分类" required>
          <Cascader v-model="companySaleCategorys" :options="categoryData" :ids="companySaleCategoryIds" :props="props"
            ref="companySaleCategorys" />
          <!-- <el-input v-model.trim="user.companySaleCategoryIds" /> -->
        </el-form-item>
        <el-form-item label="主要采购" required>
          <Cascader v-model="companyBuyCategorys" :options="categoryData" :ids="companyBuyCategoryIds" :props="props"
            ref="companyBuyCategorys" />
          <!-- <el-input v-model.trim="user.companyBuyCategoryIds" /> -->
        </el-form-item>
        <!-- <el-form-item label="企业介绍" prop="companyDescription">
          <el-input v-model.trim="user.companyDescription" type="textarea" :rows="3" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleUpdate()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import AddressCascader from '@/components/AddressCascader'
import Cascader from '@/components/Cascader'
import Upload from '@/components/Upload'
import { categoryPageVoByQo } from '@/api/product'

import { dictListByQo } from '@/api/system'
import UpImgs from '@/components/Upload/UpImgs'
import {photoOcr} from '@/api/account'
export default {
  components: { AddressCascader, Cascader, Upload, UpImgs },
  data() {
    return {
      companyTypeJson: Object.assign({}, this.$store.state.user.companyTypeJson),
      user: Object.assign({}, this.$store.getters.userInfo),
      selectedOptions: [],
      companyMatureData: [],
      companyScaleData: [],
      categoryData: [],
      companySaleCategorys: [],
      companyBuyCategorys: [],
      companySaleCategoryIds: '',
      companyBuyCategoryIds: '',
      props: { multiple: true, value: 'id', label: 'name' },
      rules: {
        companyName: [{required: true,message: '请输入',trigger: 'blur'}],
        authImage: [{required: true,message: '请输入',trigger: 'blur'}],
        cardImage: [{required: true,message: '请输入',trigger: 'blur'}],
        doorImage: [{required: true,message: '请输入',trigger: 'blur'}],
        taxNo: [{required: true,message: '请输入',trigger: 'blur'}],
        companyContactName: [{required: true,message: '请输入',trigger: 'blur'}],
        companyContactMobile: [{required: true,message: '请输入',trigger: 'blur'}],
        authNo: [{required: true,message: '请输入',trigger: 'blur'}],
        // contractNo: [{required: true,message: '请输入',trigger: 'blur'}],
      },
      otherImages: [], //其他证明图片
      baseRules: {
        companyMature: [{required: true,message: '请输入',trigger: 'blur'}],
        companyScale: [{required: true,message: '请输入',trigger: 'blur'}],
        companyEmail: [{required: true,message: '请输入',trigger: 'blur'}],
        selectedOptions: [{type: "array", required: true,message: '请输入',trigger: 'blur'}],
        companyAddress: [{required: true,message: '请输入',trigger: 'blur'}],
        companyMoney: [{required: true,message: '请输入',trigger: 'blur'}],
        companyDescription: [{required: true,message: '请输入',trigger: 'blur'}],
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  watch: {
    userInfo(val) {
      this.user = Object.assign({}, val)
      this.init(val)
    },
    companySaleCategorys(val) {
      this.$set(this.user, `companySaleCategoryIds`, this.$refs['companySaleCategorys'].getIds(val))
    },
    companyBuyCategorys(val) {
      this.$set(this.user, `companyBuyCategoryIds`, this.$refs['companyBuyCategorys'].getIds(val))
    },
    // 企业资质
    'user.authImage': {
      handler(newVal, oldVal) {
        if((newVal != oldVal) && (this.userInfo.status === 2 || this.userInfo.status === 5)){
          //ocr
          this.handleCertPic(newVal)
        }
      },
      deep: true, //深度监听对象的变化
    },
    // 身份证照片
    'user.cardImage': {
      handler(newVal, oldVal) {
        if((newVal != oldVal) && (this.userInfo.status === 2 || this.userInfo.status === 5)){
          //ocr
          this.handleIdPic(newVal)
        }
      },
      deep: true, //深度监听对象的变化
    },
  },
  created() {
    this.getCategory()
    this.getCompanyType('companyMature')
    this.getCompanyType('companyScale')
  },
  methods: {
    init(val) {
      this.$nextTick(() => {
        if (val.companyDistrictId) {
          this.selectedOptions = [val.companyProvinceId.toString(), val.companyCityId.toString(), val.companyDistrictId.toString()]
        } else {
          this.selectedOptions = ''
        }
        this.$set(this.user, 'selectedOptions', this.selectedOptions);
        this.companySaleCategoryIds = val.companySaleCategoryIds || '';
        this.companyBuyCategoryIds = val.companyBuyCategoryIds || '';

        if (this.user.otherAuthImages) {
          let array = this.user.otherAuthImages.split(",")
          var otherImages = []
          for (let index = 0; index < array.length; index++) {
            const element = array[index];
            let url = {url: element}
            otherImages.push(url)
          }
          this.$set(this, "otherImages", otherImages)
        }
      })
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.user, `companyProvinceId`, value.provinceId)
        this.$set(this.user, `companyProvinceName`, value.provinceName)
        this.$set(this.user, `companyCityId`, value.cityId)
        this.$set(this.user, `companyCityName`, value.cityName)
        this.$set(this.user, `companyDistrictId`, value.districtId)
        this.$set(this.user, `companyDistrictName`, value.districtName)
      } else {
        this.$set(this.user, `companyProvinceId`, '')
        this.$set(this.user, `companyProvinceName`, '')
        this.$set(this.user, `companyCityId`, '')
        this.$set(this.user, `companyCityName`, '')
        this.$set(this.user, `companyDistrictId`, '')
        this.$set(this.user, `companyDistrictName`, '')
      }
    },
    getCompanyType(code) {
      dictListByQo({ code: code }).then((res) => {
        this.$set(this, `${code}Data`, res)
      })
    },
    getCategory() {
      categoryPageVoByQo().then((res) => {
        this.$set(this, 'categoryData', res || [])
        if (this.$store.getters.userInfo) {
          this.init(this.$store.getters.userInfo)
        }
      })
    },
    submit(CompanyInfo) {
      this.$refs[CompanyInfo].validate((valid) => {
        if (valid) {
          var otherAuthImages = []
          if (this.otherImages && this.otherImages.length > 0) {
            for (let index = 0; index < this.otherImages.length; index++) {
              const element = this.otherImages[index];
              otherAuthImages.push(element.url)
            }
            this.$set(this.user, "otherAuthImages", otherAuthImages.toString())
          }
          
          const params = Object.assign({}, this.user)
          this.$store.dispatch('user/authMemberInfo', params).then((res) => {
            this.$message({
              message: '编辑成功',
              type: 'success',
              duration: 5 * 1000
            })
          })
        } else {
          this.$message.error("请填写必填项")
          return false;
        }
      })
    },
    handleUpdate() {
      if (!this.user.companySaleCategoryIds || this.user.companySaleCategoryIds.length === 0) {
        this.$message.error("请选择主营分类");
        return;
      }
      if (!this.user.companyBuyCategoryIds || this.user.companyBuyCategoryIds.length === 0) {
        this.$message.error("请选择主要采购");
        return;
      }

      const params = Object.assign({}, this.user);
      this.$refs['baseInfo'].validate((valid) => {
        if (valid) {
          this.$store.dispatch('user/updateMember', params).then((res) => {
            this.$message({
              message: '编辑成功',
              type: 'success',
              duration: 5 * 1000
            })
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleCertPic(url) {
      photoOcr({url: url, type: 3}).then(response => { 
        if (response && response.creditCode) {
          this.$set(this.user, "authNo", response.creditCode)
        }
      }).catch(error => {
        console.log(error);
      })
    },
    handleIdPic(url) {
      photoOcr({url: url, type: 1}).then(response => { 
        if (response && response.idNumber) {
          this.$set(this.user, "cardNo", response.idNumber)
        }
      }).catch(error => {
        console.log(error);
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.flexInput {
  display: flex;
  width: 100%;
  .el-input {
    width: auto;
    flex: 1;
  }
}
</style>
